from sklearn.svm import SVR
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, cross_val_score
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv("../data/train_pp.csv")

important_num_cols = list(df.corr()["SalePrice"][(
    df.corr()["SalePrice"] > 0.50) | (df.corr()["SalePrice"] < -0.50)].index)
cat_cols = ["MSZoning", "Utilities", "BldgType",
            "Heating", "KitchenQual", "SaleCondition", "LandSlope"]
important_cols = important_num_cols + cat_cols

df = df[important_cols]
X = df.drop("SalePrice", axis=1)
y = df["SalePrice"]
# One-Hot Encoding
X = pd.get_dummies(X, columns=cat_cols)

# Train-Test Split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)

# 评价函数


def rmse_cv(model):
    rmse = np.sqrt(-cross_val_score(model, X, y,
                   scoring="neg_mean_squared_error", cv=5)).mean()
    return rmse


def evaluation(y, predictions):
    mae = mean_absolute_error(y, predictions)
    mse = mean_squared_error(y, predictions)
    rmse = np.sqrt(mean_squared_error(y, predictions))
    r_squared = r2_score(y, predictions)
    return mae, mse, rmse, r_squared


# 标准化
important_num_cols.remove("SalePrice")

scaler = StandardScaler()
X[important_num_cols] = scaler.fit_transform(X[important_num_cols])

svr = SVR(C=100000)
svr.fit(X_train, y_train)
predictions = svr.predict(X_test)
mae, mse, rmse, r_squared = evaluation(y_test, predictions)
print("MAE:", mae)
print("MSE:", mse)
print("RMSE:", rmse)
print("R2 Score:", r_squared)
print("-"*30)
rmse_cross_val = rmse_cv(svr)
print("RMSE Cross-Validation:", rmse_cross_val)
